package com.safe.first.infrastructure.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.safe.first.common.model.R;
import com.safe.first.infrastructure.model.JwtToken;
import com.safe.first.infrastructure.service.TokenService;
import lombok.AllArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Mickey
 * @since 2022/6/11
 **/
@Component
@AllArgsConstructor
public class MySavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private final ObjectMapper objectMapper;
    private final TokenService tokenService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException {
        response.setHeader("Content-Type", "application/json");
        response.setContentType("application/json;charset=UTF-8");
        clearAuthenticationAttributes(request);
        JwtToken token = tokenService.token(authentication);
        response.getWriter().write(objectMapper.writeValueAsString(R.OK(token)));
    }

}
